<?php


namespace app\api\controller;


/**
 * Class 预排期定时器
 * @package app\api\controller
 */
class Preparetime extends \app\common\controller\Api
{
    protected $noNeedLogin = ['*'];

    /**
     * 预排期结算
     */
    public function prepare(){
        $ok = db('config')->where('name','prepare_jiesuan')->value('value');

        if (!$ok){
           return;
        }
        $list = db('user')
            ->where('prepare_status','1')
            ->limit(1000)
            ->column('id');

        if(!$list){
            db('config')->where('name','prepare_jiesuan')->update(['value'=>0]);
            return;
        }
        foreach ($list as $key => $value){
            $zhitui = db('user')->where('first_id',$value)->count();//直推人数
            $all_sons = db('user')
                ->where('tree','like','%,'.$value.',%')
                ->count('id');
            $all_sons++;//团队人数
            $prepare = db('prepare')
                ->where('zhi_num','<=',$zhitui)
                ->where('team_num','<=',$all_sons)
                ->order('team_num DESC')
                ->find();
            if ($prepare){
                //满足条件
                db('user')
                    ->where('id',$value)
                    ->inc('cb_num',$prepare['reward_cbnum'])
                    ->inc('cb_minsell',$prepare['reward_cbnum']/2)
                    ->update(['prepare_status'=>2,'prepare_send_cb'=>$prepare['reward_cbnum']]);
                setCbwater($value,$prepare['reward_cbnum'],1,'预排期结算赠送');
            }else{
                db('user')
                    ->where('id',$value)
                    ->update(['prepare_status'=>2]);
            }
        }
    }

    /**
     * 开盘3天结算
     */
    public function threeday_jiesuan(){
        $ok = db('config')->where('name','prepare_threeday')->value('value');
        if (!$ok){
            return;
        }
        $list = db('user')
            ->field('id,prepare_send_cb,cb_minsell,cb_num')
            ->where('cb_minsell','>',0)
            ->where('threeday_status','1')
            ->limit(1000)
            ->select();
        if(!$list){
            db('config')->where('name','prepare_threeday')->update(['value'=>0]);
            return;
        }
        foreach ($list as $key => $value){
            $jian = $value['prepare_send_cb']/2 + $value['cb_minsell'];
            if ($jian > $value['cb_num']){
                $jian = $value['cb_num'];
            }
            db('user')->where('id',$value['id'])->setDec('cb_num',$jian);
            setCbwater($value['id'],$jian,2,'开盘3天未卖出预排期赠送的50%,扣除');
        }
    }
}